//
//  HMPayment.swift
//  HealthMonitoring
//
//  Created by YTYanK on 28/01/2019.
//  Copyright © 2019 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON
// 支付类型
class HMPaymentMethodView: UIView {
    var signId: String?
    let paymentLogo = UIImageView()
    let paymentName = UILabel()
    let single = UIButton()
  
    
    init(_ target: Any?) {
        super.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44))
       // self.backgroundColor = UIColor.clear
        setupViews(self)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews(_ view: UIView) {
        view.addSubview(paymentLogo)
        view.addSubview(paymentName)
        view.addSubview(single)
        
        paymentLogo.topAlign(view: view)
        paymentLogo.leadingAlign(view: view, predicate: "20")
        paymentLogo.heightConstrain(predicate: "27")
        paymentLogo.widthConstrain(predicate: "30")
        paymentLogo.image = UIImage.init(named: "绿色logo")
        
        
        paymentName.centerYAlign(view: view)
        paymentName.leadingHorizontally(view: paymentLogo)
        paymentName.text = "微信支付"
        
        
        single.centerYAlign(view: view)
        single.trailingAlign(view: view)
        single.widthConstrain(predicate: "40")
        single.heightConstrain(predicate: "40")
        single.backgroundColor = .red
        single.layer.cornerRadius = 20
        
       
        
    }
    
    public func setJson(_ json: JSON) {
        
    }
}




class HMPayment: HMViewController, WXApiDelegate {
   
    let orderDetails  = UILabel()
    let sum = UILabel()
    let paymentMethod = UILabel()
    let wxPayment = HMPaymentMethodView.init(self)
    let confirmPayment = UIButton()
    /// 订单Id
    public var orderId = ""
    /// 咨询id
    public var consultId = ""
    /// 医生id
    public var doctorId = ""
    public var cost: Double = 0.0
    
    override func setupView() {
        self.title = "支付"
        view.backgroundColor = configure.shareConfigure.HMColor2
        
        view.addSubview(orderDetails)
        view.addSubview(sum)
        view.addSubview(paymentMethod)
        view.addSubview(wxPayment)
        view.addSubview(confirmPayment)
        
        
       let scrW = configure.shareConfigure.screenWidth
       let aveScrW = scrW / 2.0
       let itemH =  44
        let emptylen = orderDetails.font.pointSize
        orderDetails.topAlign(view: view)
        orderDetails.leadingAlign(view: view, predicate: "0")
        orderDetails.widthConstrain(predicate: "\(aveScrW)")
        orderDetails.heightConstrain(predicate: "\(itemH)")
        orderDetails.text = "咨询费用"
        orderDetails.backgroundColor = UIColor.white
         UILabel.setIndent(orderDetails, alignment: .left, headIndent: emptylen, tailIndent: 0.0, lineSpacing: 2.0)

        
        sum.topAlign(view: view)
        sum.trailingAlign(view: view, predicate: "0")
        sum.widthConstrain(predicate: "\(aveScrW)")
        sum.heightConstrain(predicate: "\(itemH)")
        sum.text = "\(self.cost) 元"
        sum.backgroundColor = UIColor.white
        UILabel.setIndent(sum, alignment: .right, headIndent: 0.0, tailIndent: emptylen, lineSpacing: 2.0)
        
        
        paymentMethod.topVertically(view: orderDetails, predicate: "8")
        paymentMethod.leadingAlign(view: view, predicate: "0")
        paymentMethod.trailingAlign(view: view, predicate: "0")
        paymentMethod.heightConstrain(predicate: "30")
        paymentMethod.backgroundColor = UIColor.white
        paymentMethod.text = "选择支付方式"
        UILabel.setIndent(paymentMethod, alignment: .left, headIndent: emptylen, tailIndent: 0.0, lineSpacing: 2.0)
        
        
        wxPayment.topVertically(view: paymentMethod, predicate: "0")
        wxPayment.leadingAlign(view: view, predicate: "0")
        wxPayment.trailingAlign(view: view, predicate: "0")
        wxPayment.heightConstrain(predicate: "44")
        wxPayment.backgroundColor = UIColor.white
        

        confirmPayment.heightConstrain(predicate: "44")
        confirmPayment.leadingAlign(view: view)
        confirmPayment.trailingAlign(view: view)
        confirmPayment.bottomAlign(view: view, predicate: "-16")
        confirmPayment.layer.cornerRadius = 4
        confirmPayment.backgroundColor = configure.shareConfigure.HMColor1
        confirmPayment.setTitle("确认支付", for: UIControlState.normal)
        confirmPayment.addTarget(self, action: #selector(confirm), for: UIControlEvents.touchUpInside)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    @objc func confirm(sender: UIButton) {
        print("======>>", sender);
        
//        if WXApi.isWXAppInstalled() {
            print("====>>有微信")
            //微信支付
            NetRequestTool.shareInstance.met = .get
            NetRequestTool.request(url: "user/order/wx-prepay", parameters: ["orderId": self.orderId], success: { (json) in
            
                //SDK
                let  request:PayReq = PayReq.init()
                request.partnerId = json["data"]["partnerID"].stringValue
                request.prepayId = json["data"]["prepayId"].stringValue
                request.package = json["data"]["packag"].stringValue
                request.nonceStr = json["data"]["noncestr"].stringValue
                request.timeStamp = UInt32(json["data"]["timestamp"].intValue)
                request.sign = json["data"]["sign"].stringValue
                UserDefaults.standard.set(self.orderId, forKey: "WXOrderId")
                UserDefaults.standard.set(self.consultId,forKey: "WXConsultId")
                UserDefaults.standard.set(self.doctorId, forKey: "WXDoctorId")
                WXApi.send(request)
                
//                let num = ((self.navigationController?.viewControllers.count)! - 2)
                let viewC =  self.navigationController?.viewControllers[1] as!HMDoctorService
                self.navigationController?.popToViewController(viewC, animated: true)
              
            }, fail: { (code, err) in
                print("失败===>")
                // 3
                RKDropdownAlert.title("温馨提醒!", message: "支付授权失败！")
            }) {
    
            }

//        }else {
//            RKDropdownAlert.title("温馨提醒！", message: "请下载微信App")
//        }
//
    }
    
//    //微信支付发起
//    func onReq(_ req: BaseReq!) {
//       print("======>>>", req)
//    }
//
//    //微信支付回调
//    func onResp(_ resp: BaseResp!) {
//        //真鸡测试
//        if resp.isKind(of: PayResp.classForCoder()) {
//            print("====呃呃呃")
//
//        }
//        print("====呃呃呃")
//    }

}
